package com.golang.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 跨域过滤器 解决跨域问题
 */
@Component
@Slf4j
public class GatewayCorsFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String origin = request.getHeaders().getFirst(HttpHeaders.ORIGIN);
        if (origin != null) {
            HttpHeaders respHeaders = response.getHeaders();
            respHeaders.add("Access-Control-Allow-Credentials", "true");
            respHeaders.add("Access-Control-Allow-Origin", origin);
            respHeaders.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, HEAD ,OPTIONS");
            respHeaders.add("Access-Control-Allow-Headers", "x-requested-with, Accept, Referer, User-Agent, Content-Type, Authorization, credential, X-XSRF-TOKEN, token, fileName, fileType, normal");
            respHeaders.add("Access-Control-Max-Age", "3600");
        }
        if (HttpMethod.OPTIONS.equals(request.getMethod())) {
            exchange.getResponse().setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
        return chain.filter(exchange);
    }

}
